package com.jiuxian.scheduling.tasks;

import com.jiuxian.scheduling.commons.LogInfoContext;
import com.jiuxian.scheduling.commons.SpringApplicationContext;
import com.jiuxian.scheduling.rpc.RequestRpc;
import com.jiuxian.scheduling.rpc.RequestRpcBuild;
import com.jiuxian.scheduling.servers.LogServer;
import com.jiuxian.scheduling.util.SiteUtil;
import com.jiuxian.scheduling.util.ZKClientUtil;
import com.jiuxian.scheduling.util.ZKLock;
import com.jiuxian.scheduling.vo.LogInfoVO;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by wangjingqing on 2017/12/18.
 */
public class TaskJob extends Task {

    private Logger logger = LoggerFactory.getLogger(TaskJob.class);
    private SchedingVO schedingVO;
    private ZKLock lock;

    private LogServer logServer = SpringApplicationContext.getClass(LogServer.class);

    @Override
    public boolean before(JobExecutionContext jobExecutionContext){
        Object obj = jobExecutionContext.getJobDetail().getJobDataMap().get("schedingInfo");
        if(obj != null){
            schedingVO = (SchedingVO)obj;
            lock = new ZKLock(schedingVO.getName());
            if(!lock.tryLock()){
               return false;
            }
            schedingVO.setNextDate(jobExecutionContext.getNextFireTime());
            ZKClientUtil.setDate(schedingVO.getName(),schedingVO);
            return true;
        }
        return false;
    }

    @Override
    public void doExecute(JobExecutionContext jobExecutionContext) {
        RequestRpc request = RequestRpcBuild.build(schedingVO);
        Date startTime = new Date();
        int state = 1;
        String details = "";
        try {
            Object data = request.request();
            System.out.println("返回数据："+data);
        } catch (Exception e) {
            logger.error("执行异常:"+schedingVO.getName(),e);
            state = 0;
            details = SiteUtil.getExceptionAllInfo(e.getMessage(),e.getStackTrace());
        }
        //执行用时
        Long taskTime = (new Date()).getTime() - startTime.getTime();
        LogInfoVO logInfo = new LogInfoVO();
        logInfo.setName(schedingVO.getName());
        logInfo.setTaskTime(taskTime.intValue());
        logInfo.setState(state == 1?true:false);
        logInfo.setCreatTime(SiteUtil.convertDate(new Date(),SiteUtil.FORMAT_SECOND));
        logInfo.setDetails(details);
        logServer.insertLogInfo(logInfo);

        LogInfoContext.addLogInfo(logInfo);
    }
    /**
     * 之后执行<br>
     */
    @Override
    public void after(JobExecutionContext jobExecutionContext){
        lock.unLock();
    }
}
